<?php defined('SYSPATH') or die('Access error!');
/**
 * 核心类
 */
class Core {

	// 版本信息
	const VERSION  = '1.0.0';
	const CODENAME = 'hero';

	// 日志类型
	const ERROR    = 'ERROR';
	const DEBUG    = 'DEBUG';
	const INFO     = 'INFO';
	const CRITICAL = 'CRITICAL';
	const STRACE   = 'STRACE';
	const ALERT    = 'ALERT';

	// 环境所要的常量
	const PRODUCTION  = 'production';
	const STAGING     = 'staging';
	const TESTING     = 'testing';
	const DEVELOPMENT = 'development';

	// 安全代码常量
	const FILE_SECURITY = '<?php defined(\'SYSPATH\') or die(\'Access error!\');';

	// 缓存相关: header, cache name, and data
	const FILE_CACHE = ":header \n\n// :name\n\n:data\n";

	/**
	 * @var  array  php错误等级提示
	 */
	public static $php_errors = array(
		E_ERROR              => 'Fatal Error',
		E_USER_ERROR         => 'User Error',
		E_PARSE              => 'Parse Error',
		E_WARNING            => 'Warning',
		E_USER_WARNING       => 'User Warning',
		E_STRICT             => 'Strict',
		E_NOTICE             => 'Notice',
		E_RECOVERABLE_ERROR  => 'Recoverable Error',
	);

	/**
	 * @var  当前的环境常量
	 */
	public static $environment = Core::DEVELOPMENT;

	/**
	 * @var  boolean  是否窗口启动
	 */
	public static $is_windows = FALSE;

	/**
	 * @var  boolean  magic quotes.
	 */
	public static $magic_quotes = FALSE;

	/**
	 * @var  boolean  日志相关
	 */
	public static $log_errors = FALSE;

	/**
	 * @var  boolean  安全相关
	 */
	public static $safe_mode = FALSE;

	/**
	 * @var  string  编码
	 */
	public static $charset = 'utf-8';

	/**
	 * @var  string 默认的程序路径
	 */
	public static $base_url = '/';

	/**
	 * @var  string  默认的执行文件
	 */
	public static $index_file = 'index.php';

	/**
	 * @var  boolean  配置是否启动
	 */
	public static $profiling = TRUE;

	/**
	 * @var  boolean  是否显示错误
	 */
	public static $errors = TRUE;

	/**
	 * @var  string  错误页面
	 */
	public static $error_view = 'core/error';

	/**
	 * @var  array  在关闭的时候显示的错误
	 */
	public static $shutdown_errors = array(E_PARSE, E_ERROR, E_USER_ERROR);

	/**
	 * @var  boolean  过滤
	 */
	public static $debug_escape_quotes = FALSE;

	/**
	 * @var  Kohana_Log  日志对象
	 */
	public static $log;

	/**
	 * @var  Kohana_Config  配置对象
	 */
	public static $config;

	/**
	 * @var  boolean  判断是否已经初始化框架
	 */
	protected static $_init = FALSE;

	/**
	 * @var  array   初始化载入的模块
	 */
	protected static $_modules = array();

	/**
	 * @var  array   find_classes函数的根目录
	 */
	protected static $_paths = array(APPPATH, SYSPATH);

	/**
	 * @var  array  当缓存存在时。记录缓存的路径
	 */
	protected static $_files = array();

	/**
	 * @var  boolean  如果路径发生了改变
	 */
	protected static $_files_changed = FALSE;

	/**
         * 初始化环境
	 */
	public static function init(array $settings = NULL)
	{
               // $_init  为静态变量框架只初始化一次
		if (Core::$_init)
		{
			return;
		}
		Core::$_init = TRUE;

                
                //配置   性能分析器
		if (isset($settings['profile']))
		{
			Core::$profiling = (bool) $settings['profile'];
		}
                
                
		// 启动输出页面函数
		ob_start();

                //E_DEPRECATED 在PHP >= 5.3.0中存在
		if (defined('E_DEPRECATED'))
		{
			Core::$php_errors[E_DEPRECATED] = 'Deprecated';
		}

                //配置 错误相关
		if (isset($settings['errors']))
		{
			Core::$errors = (bool) $settings['errors'];
		}
		if (Core::$errors === TRUE)
		{
			set_exception_handler(array('Core', 'exception_handler'));
			set_error_handler(array('Core', 'error_handler'));
		}

		// 收集所有的错误 在程序运行完毕
		register_shutdown_function(array('Core', 'shutdown_handler'));
                //配置错误提示页面
		if (isset($settings['error_view']))
		{
			if ( ! Core::find_file('views', $settings['error_view']))
			{
				throw new Core_Exception('error页面不存在： views/:file', array(
					':file' => $settings['error_view'],
				));
			}
			Core::$error_view = (string) $settings['error_view'];
		}

                //处理全局变量
		if (ini_get('register_globals'))
		{
			Core::globals();
		}
                
                
		Core::$is_windows = (DIRECTORY_SEPARATOR === '\\');
                
                
                //配置  编码
		if (isset($settings['charset']))
		{
			Core::$charset = strtolower($settings['charset']);
		}

		if (function_exists('mb_internal_encoding'))
		{
			mb_internal_encoding(Core::$charset);
		}

                // 配置  基本的url 
		if (isset($settings['base_url']))
		{
			Core::$base_url = rtrim($settings['base_url'], '/').'/';
		}

                //配置 默认访问的入口文件
		if (isset($settings['index_file']))
		{
			Core::$index_file = trim($settings['index_file'], '/');
		}
                
                //取得 PHP 环境变量 magic_quotes_gpc 的值
                //当 magic_quotes_gpc 打开时，所有的 ' (单引号), " (双引号), \ (反斜线) and 空字符会自动转为含有反斜线的转义字符。
		Core::$magic_quotes = (bool) get_magic_quotes_gpc();

		//过滤 get post cookie
		$_GET    = Core::sanitize($_GET);
		$_POST   = Core::sanitize($_POST);
		$_COOKIE = Core::sanitize($_COOKIE);

		// 初始化日志文件
		Core::$log = Log::instance();

		// 初始化配置文件
		Core::$config = Config::instance();
	}

	/**
	 * 注销框架
	 */
	public static function deinit()
	{
		if (Core::$_init)
		{
			//取消自动加载函数
			spl_autoload_unregister(array('Core', 'auto_load'));

			if (Core::$errors)
			{
				restore_error_handler();
				restore_exception_handler();
			}
			Core::$log = Core::$config = NULL;
			Core::$_modules = Core::$_files = array();
			Core::$_paths   = array(APPPATH, SYSPATH);
			Core::$_files_changed = FALSE;
			Core::$_init = FALSE;
		}
	}

	/**
	 *  处理全局变量
	 */
	public static function globals()
	{
		if (isset($_REQUEST['GLOBALS']) OR isset($_FILES['GLOBALS']))
		{
			echo "请求已中止.\n";
			exit(1);
		}

		$global_variables = array_keys($GLOBALS);

		$global_variables = array_diff($global_variables, array(
			'_COOKIE',
			'_ENV',
			'_GET',
			'_FILES',
			'_POST',
			'_REQUEST',
			'_SERVER',
			'_SESSION',
			'GLOBALS',
		));

		foreach ($global_variables as $name)
		{
			unset($GLOBALS[$name]);
		}
	}

	/**
	 *获取安全的method 提交的数据
	 */
	public static function sanitize($value)
	{
		if (is_array($value) OR is_object($value))
		{
			foreach ($value as $key => $val)
			{
				$value[$key] = Core::sanitize($val);
			}
		}
		elseif (is_string($value))
		{
			if (Core::$magic_quotes === TRUE)
			{
				$value = stripslashes($value);
			}

			if (strpos($value, "\r") !== FALSE)
			{
				$value = str_replace(array("\r\n", "\r"), "\n", $value);
			}
		}
		return $value;
	}

	/**
	 * 自动加载类
	 */
	public static function auto_load($class)
	{
		try
		{
			$file = str_replace('_', '/', strtolower($class));

			if ($path = Core::find_file('classes', $file))
			{
				require $path;

				return TRUE;
			}
			return FALSE;
		}
		catch (Exception $e)
		{
			Core::exception_handler($e);
			die;
		}
	}

	/**
	 * 设置 modules
	 * @param   array  modules的路径
	 * @return  array  存在的modules
	 */
	public static function modules(array $modules = NULL)
	{
		if ($modules === NULL)
		{
			return Core::$_modules;
		}

		$paths = array(APPPATH);

		foreach ($modules as $name => $path)
		{
			if (is_dir($path))
			{
				$paths[] = $modules[$name] = realpath($path).DIRECTORY_SEPARATOR;
			}
			else
			{
				unset($modules[$name]);
			}
		}
		// 保存系统目录
		$paths[] = SYSPATH;
		Core::$_paths = $paths;
		Core::$_modules = $modules;

		foreach (Core::$_modules as $path)
		{
                       // 如果module有自己的配置文件先引入配置文件
			$init = $path.'init'.EXT;

			if (is_file($init))
			{
				require_once $init;
			}
		}

		return Core::$_modules;
	}

	/**
	 * 得到操作的文件路径   数组
	 */
	public static function include_paths()
	{
		return Core::$_paths;
	}

	/**
         *  查找所需要 的文件
         */
	public static function find_file($dir, $file, $ext = NULL, $array = FALSE)
	{
              
		if ($ext === NULL)
		{
			$ext = EXT;
		}
		elseif ($ext)
		{
			$ext = ".{$ext}";
		}
		else
		{
			$ext = '';
		}

		$path = $dir.DIRECTORY_SEPARATOR.$file.$ext;
		if (Core::$profiling === TRUE AND class_exists('Profiler', FALSE))
		{
			$benchmark = Profiler::start('Core', __FUNCTION__);
		}

		if ($array OR $dir === 'config' OR $dir === 'i18n' OR $dir === 'messages')
		{
			$paths = array_reverse(Core::$_paths);

			$found = array();

			foreach ($paths as $dir)
			{
				if (is_file($dir.$path))
				{
					$found[] = $dir.$path;
				}
			}
		}
		else
		{
                    
			$found = FALSE;

			foreach (Core::$_paths as $dir)
			{
				if (is_file($dir.$path))
				{
					$found = $dir.$path;

					break;
				}
			}
		}


		if (isset($benchmark))
		{
			Profiler::stop($benchmark);
		}
		return $found;
	}

	/**
	 * 获取指定目录下的所有文件
	 */
	public static function list_files($directory = NULL, array $paths = NULL)
	{
		if ($directory !== NULL)
		{
			$directory .= DIRECTORY_SEPARATOR;
		}

		if ($paths === NULL)
		{
			$paths = Core::$_paths;
		}

		$found = array();

		foreach ($paths as $path)
		{
			if (is_dir($path.$directory))
			{
				$dir = new DirectoryIterator($path.$directory);

				foreach ($dir as $file)
				{
					$filename = $file->getFilename();

					if ($filename[0] === '.' OR $filename[strlen($filename)-1] === '~')
					{
						continue;
					}

					$key = $directory.$filename;

					if ($file->isDir())
					{
						if ($sub_dir = Core::list_files($key, $paths))
						{
							if (isset($found[$key]))
							{
								$found[$key] += $sub_dir;
							}
							else
							{
								$found[$key] = $sub_dir;
							}
						}
					}
					else
					{
						if ( ! isset($found[$key]))
						{
							$found[$key] = realpath($file->getPathName());
						}
					}
				}
			}
		}

		ksort($found);

		return $found;
	}

        /**
         * 载入一个文件
         */
	public static function load($file)
	{
		return include $file;
	}

	/**
         *  获取所需要的配置文件
	 */
	public static function config($group)
	{
		static $config;

		if (strpos($group, '.') !== FALSE)
		{
			list ($group, $path) = explode('.', $group, 2);
		}

		if ( ! isset($config[$group]))
		{
			$config[$group] = Core::$config->load($group);
		}

		if (isset($path))
		{
			return Arr::path($config[$group], $path, NULL, '.');
		}
		else
		{
			return $config[$group];
		}
	}
	

	
/******************************************************以下代码为调试使用********************************************************************/

	/**
	 * PHP错误处理程序，将所有的错误到ErrorExceptions。此处理程序方面打开error_reporting设置。
	 * @throws  ErrorException
	 * @return  TRUE
	 */
	public static function error_handler($code, $error, $file = NULL, $line = NULL)
	{
		if (error_reporting() & $code)
		{
			throw new ErrorException($error, $code, 0, $file, $line);
		}
		return TRUE;
	}

	public static function exception_handler(Exception $e)
	{
		try
		{
			$type    = get_class($e);
			$code    = $e->getCode();
			$message = $e->getMessage();
			$file    = $e->getFile();
			$line    = $e->getLine();

			$error = Core::exception_text($e);

			if (is_object(Core::$log))
			{
				Core::$log->add(Core::ERROR, $error);
				Core::$log->write();
			}

			$trace = $e->getTrace();

			if ($e instanceof ErrorException)
			{
				if (isset(Core::$php_errors[$code]))
				{
					$code = Core::$php_errors[$code];
				}

				if (version_compare(PHP_VERSION, '5.3', '<'))
				{
					for ($i = count($trace) - 1; $i > 0; --$i)
					{
						if (isset($trace[$i - 1]['args']))
						{
							$trace[$i]['args'] = $trace[$i - 1]['args'];
							unset($trace[$i - 1]['args']);
						}
					}
				}
			}

			if ( ! headers_sent())
			{
				header('Content-Type: text/html; charset='.Core::$charset, TRUE, 500);
			}
			ob_start();
			include Core::find_file('views', Core::$error_view);
			echo ob_get_clean();

			return TRUE;
		}
		catch (Exception $e)
		{
			ob_get_level() and ob_clean();
			echo Core::exception_text($e), "\n";
			exit(1);
		}
	}

	/**
	 * 捕获过程中未发现的错误的错误处理程序，如E_PARSE。
	 *
	 * @uses    Core::exception_handler
	 * @return  void
	 */
	public static function shutdown_handler()
	{
		if ( ! Core::$_init)
		{
			return;
		}



		if (Core::$errors AND $error = error_get_last() AND in_array($error['type'], Core::$shutdown_errors))
		{
			ob_get_level() and ob_clean();

			Core::exception_handler(new ErrorException($error['message'], $error['type'], 0, $error['file'], $error['line']));

			exit(1);
		}
	}

	/**
	 * 获取一行异常：
	 *
	 * @param   object  Exception
	 * @return  string
	 */
	public static function exception_text(Exception $e)
	{
		return sprintf('%s [ %s ]: %s ~ %s [ %d ]',
			get_class($e), $e->getCode(), strip_tags($e->getMessage()), Core::debug_path($e->getFile()), $e->getLine());
	}

	/**
	 * 返回一个HTML的任意数量的字符串的调试信息变量：
	 *     echo Core::debug($foo, $bar, $baz);
	 * @param   mixed   variable to debug
	 * @param   ...
	 * @return  string
	 */
	public static function debug()
	{
		if (func_num_args() === 0)
			return;

		$variables = func_get_args();

		$output = array();
		foreach ($variables as $var)
		{
			$output[] = Core::_dump($var, 1024);
		}

		return '<pre class="debug">'.implode("\n", $output).'</pre>';
	}

	/**
	 * 返回一个HTML字符串的一个单一变量的信息。
	 * @param   mixed 
	 * @param   integer
	 * @return  string
	 */
	public static function dump($value, $length = 128)
	{
		return Core::_dump($value, $length);
	}

	protected static function _dump( & $var, $length = 128, $level = 0)
	{
		if ($var === NULL)
		{
			return '<small>NULL</small>';
		}
		elseif (is_bool($var))
		{
			return '<small>bool</small> '.($var ? 'TRUE' : 'FALSE');
		}
		elseif (is_float($var))
		{
			return '<small>float</small> '.$var;
		}
		elseif (is_resource($var))
		{
			if (($type = get_resource_type($var)) === 'stream' AND $meta = stream_get_meta_data($var))
			{
				$meta = stream_get_meta_data($var);

				if (isset($meta['uri']))
				{
					$file = $meta['uri'];

					if (function_exists('stream_is_local'))
					{
						if (stream_is_local($file))
						{
							$file = Core::debug_path($file);
						}
					}

					return '<small>resource</small><span>('.$type.')</span> '.htmlspecialchars($file, ENT_NOQUOTES, Core::$charset);
				}
			}
			else
			{
				return '<small>resource</small><span>('.$type.')</span>';
			}
		}
		elseif (is_string($var))
		{
			$var = UTF8::clean($var, Core::$charset);

			if (UTF8::strlen($var) > $length)
			{
				$str = htmlspecialchars(UTF8::substr($var, 0, $length), ENT_NOQUOTES, Core::$charset).'&nbsp;&hellip;';
			}
			else
			{
				$str = htmlspecialchars($var, ENT_NOQUOTES, Core::$charset);
			}

			if (Core::$debug_escape_quotes)
			{
				$str = str_replace('"', '\\"', $str);
			}

			return '<small>string</small><span>('.strlen($var).')</span> "'.$str.'"';
		}
		elseif (is_array($var))
		{
			$output = array();

			$space = str_repeat($s = '    ', $level);

			static $marker;

			if ($marker === NULL)
			{
				$marker = uniqid("\x00");
			}

			if (empty($var))
			{
				// TODO
			}
			elseif (isset($var[$marker]))
			{
				$output[] = "(\n$space$s*RECURSION*\n$space)";
			}
			elseif ($level < 5)
			{
				$output[] = "<span>(";

				$var[$marker] = TRUE;
				foreach ($var as $key => & $val)
				{
					if ($key === $marker) continue;
					if ( ! is_int($key))
					{
						$key = '"'.htmlspecialchars($key, ENT_NOQUOTES, self::$charset).'"';
					}

					$output[] = "$space$s$key => ".Core::_dump($val, $length, $level + 1);
				}
				unset($var[$marker]);

				$output[] = "$space)</span>";
			}
			else
			{
				$output[] = "(\n$space$s...\n$space)";
			}

			return '<small>array</small><span>('.count($var).')</span> '.implode("\n", $output);
		}
		elseif (is_object($var))
		{
			$array = (array) $var;

			$output = array();

			$space = str_repeat($s = '    ', $level);

			$hash = spl_object_hash($var);

			static $objects = array();

			if (empty($var))
			{
				// TODO
			}
			elseif (isset($objects[$hash]))
			{
				$output[] = "{\n$space$s*RECURSION*\n$space}";
			}
			elseif ($level < 10)
			{
				$output[] = "<code>{";

				$objects[$hash] = TRUE;
				foreach ($array as $key => & $val)
				{
					if ($key[0] === "\x00")
					{
						$access = '<small>'.(($key[1] === '*') ? 'protected' : 'private').'</small>';
						$key = substr($key, strrpos($key, "\x00") + 1);
					}
					else
					{
						$access = '<small>public</small>';
					}

					$output[] = "$space$s$access $key => ".Core::_dump($val, $length, $level + 1);
				}
				unset($objects[$hash]);

				$output[] = "$space}</code>";
			}
			else
			{
				$output[] = "{\n$space$s...\n$space}";
			}

			return '<small>object</small> <span>'.get_class($var).'('.count($array).')</span> '.implode("\n", $output);
		}
		else
		{
			return '<small>'.gettype($var).'</small> '.htmlspecialchars(print_r($var, TRUE), ENT_NOQUOTES, Core::$charset);
		}
	}

	public static function debug_path($file)
	{
		if (strpos($file, APPPATH) === 0)
		{
			$file = 'APPPATH'.DIRECTORY_SEPARATOR.substr($file, strlen(APPPATH));
		}
		elseif (strpos($file, SYSPATH) === 0)
		{
			$file = 'SYSPATH'.DIRECTORY_SEPARATOR.substr($file, strlen(SYSPATH));
		}
		elseif (strpos($file, MODPATH) === 0)
		{
			$file = 'MODPATH'.DIRECTORY_SEPARATOR.substr($file, strlen(MODPATH));
		}
		elseif (strpos($file, ROOT_PATH) === 0)
		{
			$file = 'ROOT_PATH'.DIRECTORY_SEPARATOR.substr($file, strlen(ROOT_PATH));
		}

		return $file;
	}

	/**
         * echo Core::debug_source(__FILE__, __LINE__);
         * @param type $file
         * @param type $line_number
         * @param type $padding
         * @return boolean 
         */
	public static function debug_source($file, $line_number, $padding = 5)
	{
		if ( ! $file OR ! is_file($file) OR ! is_readable($file))
		{
			return FALSE;
		}

		$file = fopen($file, 'r');
		$line = 0;

		$range = array('start' => $line_number - $padding, 'end' => $line_number + $padding);

		$format = '% '.strlen($range['end']).'d';

		$source = '';
		while (($row = fgets($file)) !== FALSE)
		{
			if (++$line > $range['end'])
				break;

			if ($line >= $range['start'])
			{
				$row = htmlspecialchars($row, ENT_NOQUOTES, Core::$charset);

				$row = '<span class="number">'.sprintf($format, $line).'</span> '.$row;

				if ($line === $line_number)
				{
					$row = '<span class="line highlight">'.$row.'</span>';
				}
				else
				{
					$row = '<span class="line">'.$row.'</span>';
				}

				$source .= $row;
			}
		}
		fclose($file);
		return '<pre class="source"><code>'.$source.'</code></pre>';
	}

	/**
	 * 返回HTML字符串数组的每一步回溯。
	 *
	 *     echo implode('<br/>', Core::trace());
	 *
	 * @param   string 
	 * @return  string
	 */
	public static function trace(array $trace = NULL)
	{
		if ($trace === NULL)
		{
			$trace = debug_backtrace();
		}

		$statements = array('include', 'include_once', 'require', 'require_once');

		$output = array();
		foreach ($trace as $step)
		{
			if ( ! isset($step['function']))
			{
				continue;
			}

			if (isset($step['file']) AND isset($step['line']))
			{
				$source = Core::debug_source($step['file'], $step['line']);
			}

			if (isset($step['file']))
			{
				$file = $step['file'];

				if (isset($step['line']))
				{
					$line = $step['line'];
				}
			}

			$function = $step['function'];

			if (in_array($step['function'], $statements))
			{
				if (empty($step['args']))
				{
					$args = array();
				}
				else
				{
					$args = array(Core::debug_path($step['args'][0]));
				}
			}
			elseif (isset($step['args']))
			{
				if ( ! function_exists($step['function']) OR strpos($step['function'], '{closure}') !== FALSE)
				{
					$params = NULL;
				}
				else
				{
					if (isset($step['class']))
					{
						if (method_exists($step['class'], $step['function']))
						{
							$reflection = new ReflectionMethod($step['class'], $step['function']);
						}
						else
						{
							$reflection = new ReflectionMethod($step['class'], '__call');
						}
					}
					else
					{
						$reflection = new ReflectionFunction($step['function']);
					}

					$params = $reflection->getParameters();
				}

				$args = array();

				foreach ($step['args'] as $i => $arg)
				{
					if (isset($params[$i]))
					{
						$args[$params[$i]->name] = $arg;
					}
					else
					{
						$args[$i] = $arg;
					}
				}
			}

			if (isset($step['class']))
			{
				$function = $step['class'].$step['type'].$step['function'];
			}

			$output[] = array(
				'function' => $function,
				'args'     => isset($args)   ? $args : NULL,
				'file'     => isset($file)   ? $file : NULL,
				'line'     => isset($line)   ? $line : NULL,
				'source'   => isset($source) ? $source : NULL,
			);

			unset($function, $args, $file, $line, $source);
		}

		return $output;
	}

}
